﻿using System;
using System.Collections.Generic;
using System.Linq;
using Altairis.FluffyCloud.Data;

namespace Altairis.FluffyCloud.WebCore.Pages.Forum {

    public partial class Create : System.Web.UI.Page {

        public IEnumerable<object> CategoryList_GetData() {
            using (var dc = new FluffyDbContext()) {
                var categories = dc.TopicCategories.AsQueryable();
                if (!System.Web.Security.Roles.IsUserInRole(Role.AdministratorsRoleName)) categories = categories.Where(x => !x.IsSystemCategory);
                var q = from c in categories
                        orderby c.Name
                        select new {
                            Text = c.Name + (c.IsSystemCategory ? " (systémová)" : ""),
                            Value = c.TopicCategoryId
                        };
                return q.ToArray();
            }
        }

        protected void ButtonCreateTopic_Click(object sender, EventArgs e) {
            if (!this.IsValid) return;

            using (var dc = new FluffyDbContext()) {
                // Check if topic name is unique
                var topicName = this.NameTextBox.Text.Trim();
                if (dc.Topics.Any(x => x.Name.Equals(topicName, StringComparison.CurrentCultureIgnoreCase))) {
                    this.ModelState.AddModelError("ForumAlreadyExists", "Fórum s tímto nebo podobným názvem již existuje");
                    return;
                }

                // Add topic
                var topicCategoryId = int.Parse(this.CategoryList.SelectedValue);
                var newTopic = dc.Topics.Add(new Topic {
                    TopicCategoryId = topicCategoryId,
                    Description = this.DescriptionTextBox.Text,
                    Name = topicName,
                    UserName = this.User.Identity.Name
                });
                dc.SaveChanges();

                // Set default ACL - everyone can read and write
                dc.TopicAclEntries.Add(new TopicAclEntry { TopicId = newTopic.TopicId, RoleName = Role.EveryoneRoleName, Operation = TopicAclEntry.OperationRead, Action = true });
                dc.TopicAclEntries.Add(new TopicAclEntry { TopicId = newTopic.TopicId, RoleName = Role.EveryoneRoleName, Operation = TopicAclEntry.OperationPost, Action = true });

                // Set other ACL
                if (this.NoMinorsCheckBox.Checked) dc.TopicAclEntries.Add(new TopicAclEntry { TopicId = newTopic.TopicId, RoleName = Role.MinorsRoleName, Operation = TopicAclEntry.OperationRead, Action = false });
                if (this.AllowEditCheckBox.Checked) dc.TopicAclEntries.Add(new TopicAclEntry { TopicId = newTopic.TopicId, RoleName = Role.EveryoneRoleName, Operation = TopicAclEntry.OperationEdit, Action = true });
                if (this.AllowDeleteCheckBox.Checked) dc.TopicAclEntries.Add(new TopicAclEntry { TopicId = newTopic.TopicId, RoleName = Role.EveryoneRoleName, Operation = TopicAclEntry.OperationDeleteOwn, Action = true });

                // Add initial message
                dc.TopicPosts.Add(new TopicPost {
                    TopicId = newTopic.TopicId,
                    Text = this.FirstMessageTextBox.Text,
                    UserName = this.User.Identity.Name,
                    IpAddress = this.Request.UserHostAddress
                });
                dc.SaveChanges();

                // Setup links
                this.LinkGo.NavigateUrl = this.GetRouteUrl("ForumDetail", new { id = newTopic.TopicId });
                this.LinkSettings.NavigateUrl = this.GetRouteUrl("ForumSettings", new { id = newTopic.TopicId });
                this.LinkAcl.NavigateUrl = this.GetRouteUrl("ForumAcl", new { id = newTopic.TopicId });
                this.LiteralMessage.Text = string.Format(this.LiteralMessage.Text, topicName);
                this.PageMultiView.SetActiveView(this.ViewResult);
            }
        }

        protected void Page_Load(object sender, EventArgs e) {
        }
    }
}